package org.ztr.yanai.blog.interceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.ztr.yanai.blog.utils.IpUtil;

/**
 * @Author: ZhaoTR
 * @Date: Created in 2025/11/22 14:30
 * @Description: 日志拦截器，记录请求和响应的详细信息
 * @Version: 1.0
 */
@Slf4j
@Component
public class LogInterceptor implements HandlerInterceptor {

    private static final String START_TIME = "startTime";

    @Override
    public boolean preHandle(HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler) {
        // 记录请求开始时间
        request.setAttribute(START_TIME, System.currentTimeMillis());
        
        String requestURI = request.getRequestURI();
        String method = request.getMethod();
        String ip = IpUtil.getClientIp(request);
        
        log.info("收到请求 => {} {} 来自IP: {}", method, requestURI, ip);
        
        return true;
    }

    @Override
    public void postHandle(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler, ModelAndView modelAndView) {
        // 可以在这里处理响应前的逻辑
        // 例如：记录响应内容大小、添加响应头等
        
        // 记录响应内容长度
        long contentLength = response.getBufferSize();
        if (contentLength > 0) {
            log.debug("响应内容长度: {} bytes", contentLength);
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler, Exception ex) {
        Long startTime = (Long) request.getAttribute(START_TIME);
        if (startTime != null) {
            long endTime = System.currentTimeMillis();
            long executeTime = endTime - startTime;
            
            String requestURI = request.getRequestURI();
            int status = response.getStatus();
            
            log.info("请求完成 => {} 状态码: {} 耗时: {}ms", requestURI, status, executeTime);
            
            if (ex != null) {
                log.error("请求异常: ", ex);
            }
        }
    }
}
